package com.harmony.fast.rpc.slice;

import com.google.gson.Gson;
import com.harmony.fast.rpc.ResourceTable;
import com.harmony.fast.rpc.service.RemoteService;
import com.harmony.rpc.HarmonyRpc;
import com.harmony.rpc.entity.RemoteRequest;
import com.harmony.rpc.remote.ProxyRemote;
import com.task.controller.annotation.Param;
import com.task.controller.annotation.Parameter;
import com.task.controller.annotation.Parser;
import com.task.controller.annotation.UITask;
import com.task.controller.param.impl.MapParser;
import com.task.controller.parser.impl.LocalDateTimeParser;
import com.task.controller.trusteeship.TaskRegister;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.bundle.ElementName;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class MainAbilitySlice extends AbilitySlice implements TaskRegister {

    private Text text;

    private ProxyRemote proxyRemote;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        text = findComponentById(ResourceTable.Id_text_helloworld);
        // 注册abilitySlice中，被调用的方法
        registerTask(this);
        Intent.OperationBuilder operationBuilder = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(RemoteService.class)
                .withDeviceId("");
        Intent i = new Intent();
        i.setOperation(operationBuilder.build());
        // 连接ability
        connectAbility(i, new IAbilityConnection() {
            @Override
            public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
                proxyRemote = HarmonyRpc.getInstance().createProxy();
                getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
                    RemoteRequest remoteRequest = new RemoteRequest();
                    remoteRequest.setId(UUID.randomUUID().toString().replace("-", ""));
                    // 指定RemoteService中被调用的方法资源
                    remoteRequest.setResource("show/toast");
                    Map<String, String> map = new HashMap<>();
                    while (true) {
                        try {
                            // 添加被传递的参数
                            map.put("message", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                            remoteRequest.setData(new Gson().toJson(map));
                            // 向RemoteService发送功能调用申请
                            proxyRemote.sendRequest(100, iRemoteObject, remoteRequest, null);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onAbilityDisconnectDone(ElementName elementName, int i) {

            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregister(this);
    }

    /**
     * abilitySlice中被开放的接口，此方法上使用Parser注解指定方法的原始参数解析器，使用Param注解指定注入到方法中的参数的名称，使用Parameter注解指定特殊类型的参数解析器
     *
     * @param localDateTime 时间对象参数
     */
    @UITask(value = "set/text", isAsync = true)
    @Parser(cls = MapParser.class)
    private void setText(@Param(name = "text") @Parameter(parser = LocalDateTimeParser.class) LocalDateTime localDateTime) {
        this.text.setText(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime));
    }
}
